using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Diagnostics;

namespace PortugalPremiumRealEstate
{
    public partial class GetImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string idImg = Request["idImg"];
            if (string.IsNullOrEmpty(idImg))
                return;

            byte[] imgContents = Cache["ImageCache" + idImg] as byte[];
            if (imgContents == null)
            {
                imgContents = GetImageFromBd(idImg);
            }

            Response.ContentType = "image/jpeg";
            Response.BinaryWrite(imgContents);
        }

        private byte[] GetImageFromBd(string idImg)
        {
            byte[] imgContents = null;
            Database database = DatabaseFactory.CreateDatabase("OlympusSoftware");
            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[GetOpportunityImage]");
            database.AddInParameter(storedProcCommand, "@imageId", DbType.Int32, int.Parse(idImg));
            using (IDataReader reader = database.ExecuteReader(storedProcCommand))
            {
                while (reader.Read())
                {
                    imgContents = reader.GetValue(0) as Byte[];
                }
            }
            Cache["ImageCache" + idImg] = imgContents;
            return imgContents;
        }
    }
}
